﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ODS.Config;
using ODS.ViewModel;
using ODS.Utils;
using ODS.WebService.DeviceData;
using ODS.Model;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Diagnostics;

namespace ODS
{
    public partial class DetailDevicePage : PhoneApplicationPage
    {
        
        private Control currentView ;
        private DeviceModel currentDeviceModel;

        bool IsDataLoaded = false;
        public bool IsShowingPopUp = false;

        public DetailDevicePage()
        {
            InitializeComponent();

            currentView = GetPositionView;

            GetPositionView.ParentView = this;
            ImmobilizeView.ParentView = this;
            BlastView.ParentView = this;
            MessageNotificationView.ParentView = this;

            currentDeviceModel = App.currentDeviceModel;

            tbl_deviceName.Text = currentDeviceModel.VehicleName.ToUpper();
            tbl_RemainingRequestNumber.Text = currentDeviceModel.RemainingRequestNumber;

            TotalMessageViewModel totalMessageVM = App.MainViewModel.getDeviceViewModelFromDeviceIMEI(currentDeviceModel.DeviceIMEI).TotalMessageViewModel;
            this.DataContext = totalMessageVM;

            //For scroll bottom menu
            MaxTranformY = (int)slidingMenu.Height - slidingMenu.GetHeightTopBar();
            AnimationUtil.getInstance().OnAnimationCompleted += DetailDevicePage_OnAnimationCompleted;

            //pop up
            sb_fadeOut_popUp.Completed += sb_fadeOut_popUp_Completed;
            sb_fadeOut_ChooseLocationView.Completed += sb_fadeOut_ShowLocation_Completed;
        }

        

        void sb_fadeOut_popUp_Completed(object sender, EventArgs e)
        {
            popupMessage.IsOpen = false;
        }

        void sb_fadeOut_ShowLocation_Completed(object sender, EventArgs e)
        {
            showLocationView.Visibility = Visibility.Collapsed;
        }

        public void showPopUpWithAnimation(String message)
        {
            tbl_message.Text = message;

            RootPopupBorder.Opacity = 0;
            IsShowingPopUp = true;
            popupMessage.IsOpen = true;
            sb_fadeIn_popUp.Begin();
        }

        public void hiddenPopUpWithAnimation()
        {
            RootPopupBorder.Opacity = 1;
            IsShowingPopUp = false;
            sb_fadeOut_popUp.Begin();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            scrollDownSlidingMenu();
            slidingMenu.HiddenImageSelected();

            AnimationUtil.getInstance().OnAnimationCompleted -= DetailDevicePage_OnAnimationCompleted;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
             base.OnNavigatedTo(e);

             AnimationUtil.getInstance().OnAnimationCompleted += DetailDevicePage_OnAnimationCompleted;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (!isMenuDowning)
            {
                scrollDownSlidingMenuWithAnimation();
                e.Cancel = true;
            }

            if (currentView == MessageNotificationView)
            {
                if (IsShowingPopUp)
                {
                    hiddenPopUpWithAnimation();
                    e.Cancel = true;
                }
            }
            
            base.OnBackKeyPress(e);
        }

        public void showWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Visible;
        }

        public void hiddenWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Collapsed;
        }

        public bool IsLoading()
        {
            return progressBar_waiting.Visibility == Visibility.Visible ? true : false;
        }


        private void showView(Control view)
        {
            currentView.Visibility = Visibility.Collapsed;
            view.Visibility = Visibility.Visible;

            currentView = view;
        }


        private void btn_getPosition_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (currentView != GetPositionView)
            {
                showView(GetPositionView);

                img_getPosition.Source = new BitmapImage(new Uri(@"/Assets/images/Get location icon (selected).png", UriKind.Relative));
                img_starter.Source = new BitmapImage(new Uri(@"/Assets/images/Starter kill icon.png", UriKind.Relative));
                img_blast.Source = new BitmapImage(new Uri(@"/Assets/images/Blast icon.png", UriKind.Relative));
                img_message.Source = new BitmapImage(new Uri(@"/Assets/images/message icon.png", UriKind.Relative));
            }

        }

        private void btn_starter_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (currentView != ImmobilizeView)
            {
                showView(ImmobilizeView);

                img_getPosition.Source = new BitmapImage(new Uri(@"/Assets/images/Get location icon.png", UriKind.Relative));
                img_starter.Source = new BitmapImage(new Uri(@"/Assets/images/Starter kill icon(selected).png", UriKind.Relative));
                img_blast.Source = new BitmapImage(new Uri(@"/Assets/images/Blast icon.png", UriKind.Relative));
                img_message.Source = new BitmapImage(new Uri(@"/Assets/images/message icon.png", UriKind.Relative));
            }
        }

        private void btn_blast_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (currentView != BlastView)
            {
                showView(BlastView);

                img_getPosition.Source = new BitmapImage(new Uri(@"/Assets/images/Get location icon.png", UriKind.Relative));
                img_starter.Source = new BitmapImage(new Uri(@"/Assets/images/Starter kill icon.png", UriKind.Relative));
                img_blast.Source = new BitmapImage(new Uri(@"/Assets/images/Blast Icon (selected).png", UriKind.Relative));
                img_message.Source = new BitmapImage(new Uri(@"/Assets/images/message icon.png", UriKind.Relative));
            }
        }

        private async void btn_message_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (currentView != MessageNotificationView)
            {
                showView(MessageNotificationView);

                img_getPosition.Source = new BitmapImage(new Uri(@"/Assets/images/Get location icon.png", UriKind.Relative));
                img_starter.Source = new BitmapImage(new Uri(@"/Assets/images/Starter kill icon.png", UriKind.Relative));
                img_blast.Source = new BitmapImage(new Uri(@"/Assets/images/Blast icon.png", UriKind.Relative));
                img_message.Source = new BitmapImage(new Uri(@"/Assets/images/message icon (selected).png", UriKind.Relative));


            }

            showWaiting();
            if (MessageNotificationView.IsAllMessageTab)
                await App.MainViewModel.loadListMessagesOfCurrentDevice(currentDeviceModel, Constants.SIZE_PAGE, 0);
            else
                await App.MainViewModel.loadListUnreadMessagesOfCurrentDevice(currentDeviceModel, Constants.SIZE_PAGE, 0);
            hiddenWaiting();

            
        }

        private void btn_setting_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/SettingPage.xaml", UriKind.Relative));
        }

        private void btn_back_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        public void showChooseLocation()
        {
            showLocationView.Visibility = Visibility.Visible;
            showLocationView.Opacity = 0;
            sb_fadeIn_ChooseLocationView.Begin();

            showLocationView.parentView = this;
            showLocationView.ShowCurrentLocation(currentDeviceModel);
        }

        public void hiddenChooseLocation()
        {
            sb_fadeOut_ChooseLocationView.Begin();
        }


        bool isTapOnRootPopupBorder = false;
        private void grid_rootLayoutPopup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (!isTapOnRootPopupBorder)
            {
                hiddenPopUpWithAnimation();
            }
            isTapOnRootPopupBorder = false;
        }

        private void RootPopupBorder_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            isTapOnRootPopupBorder = true;
        }

        #region handle scroll bottom menu
        void DetailDevicePage_OnAnimationCompleted(bool isScrollDown)
        {
            if (isScrollDown)
            {
                currentView.IsEnabled = true;
            }
            else
            {
                currentView.IsEnabled = false;
            }
        }

        private void scrollDownSlidingMenu()
        {
            isMenuDowning = true;
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            transform.Y = 0;

        }

        private void scrollDownSlidingMenuWithAnimation()
        {
            isMenuDowning = true;
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            int Y = (int)transform.Y;
            AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);

        }



        private const int LIMIT_SCROLL = 100;
        bool isMenuDowning = true;
        int MaxTranformY = 0;
        private bool checkIsTapOnTopOfSlidingMenu(Point point)
        {
            if (showLocationView.Visibility == Visibility.Visible)
                return false;

            GeneralTransform gt = ((UIElement)slidingMenu).TransformToVisual(this);
            Point pointOdSlidingMenu = gt.Transform(new Point(0, 0));

            if (point.Y >= pointOdSlidingMenu.Y && point.Y <= pointOdSlidingMenu.Y + slidingMenu.GetHeightTopBar())
                return true;
            return false;
        }

        Point Point_Start;
        Point point_Move;
        int offset = 0;

        bool IsMouseEnterOnTopBar = false;

        private void LayoutRoot_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_MouseEnter");

            Point_Start = e.GetPosition((UIElement)sender);
            point_Move = Point_Start;

            if (checkIsTapOnTopOfSlidingMenu(Point_Start))
            {
                IsMouseEnterOnTopBar = true;

                currentView.IsEnabled = false;

                if (!isMenuDowning)
                {
                    slidingMenu.UnRegisterEventMouseForGrids();
                }
                


            }
            else
                IsMouseEnterOnTopBar = false;
        }

        private void LayoutRoot_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (isTap)
            {
                isTap = false;
                return;
            }

            if (!IsMouseEnterOnTopBar)
                return;

            if (slidingMenu.IsUnRegisterEventMouseForGrids)
            {
                slidingMenu.RegisterEventMouseForGrids();
            }

            Debug.WriteLine("LayoutRoot_MouseLeave");
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            int Y = (int)transform.Y;

            if (transform.Y < -(MaxTranformY - LIMIT_SCROLL))
            {
                //sb_scrollMenuUp.Begin();

                AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                isMenuDowning = false;


            }
            else if (transform.Y > -LIMIT_SCROLL)
            {
                //sb_scrollMenuDown.Begin();

                AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                isMenuDowning = true;
            }
            else
            {
                if (offset > 0)
                {
                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                    isMenuDowning = true;

                }
                else
                {
                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                    isMenuDowning = false;
                }
            }
        }

        private void LayoutRoot_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_MouseMove");

            if (!IsMouseEnterOnTopBar)
                return;

            var transform = slidingMenu.RenderTransform as TranslateTransform;

            point_Move = e.GetPosition((UIElement)sender);

            offset = (int)(point_Move.Y - Point_Start.Y);

            Point_Start = point_Move;

            Debug.WriteLine("offset: " + offset);

            if ((transform.Y <= -MaxTranformY && offset < 0))
            {
                isMenuDowning = false;

                currentView.IsEnabled = false;
                return;
            }

            if ((transform.Y >= 0 && offset > 0))
            {
                isMenuDowning = true;

                currentView.IsEnabled = true;
                return;
            }

            transform.Y += offset;

            if (transform.Y < -MaxTranformY)
                transform.Y = -MaxTranformY;
            if (transform.Y > 0)
                transform.Y = 0;

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {

                slidingMenu.UpdateLayout();
            });


            Debug.WriteLine("MouseMove: " + point_Move);
        }

        bool isTap = false;

        private void LayoutRoot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_Tap");
            isTap = true;

            Point Point_click = e.GetPosition((UIElement)sender);

            if (checkIsTapOnTopOfSlidingMenu(Point_click))
            {
                var transform = slidingMenu.RenderTransform as TranslateTransform;
                int Y = (int)transform.Y;

                currentView.IsEnabled = false;

                if (isMenuDowning)
                {
                    //sb_scrollMenuUp.Begin();

                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                    isMenuDowning = false;
                }
                else
                {
                    //sb_scrollMenuDown.Begin();

                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                    isMenuDowning = true;
                }
            }

            if (slidingMenu.IsUnRegisterEventMouseForGrids)
            {
                slidingMenu.RegisterEventMouseForGrids();
            }
        }
        #endregion
    }
}